#include <sys/socket.h> // socket, bind, listen, accept
#include <netinet/in.h> // sockaddr_in
#include <arpa/inet.h> // inet_addr
#include <fcntl.h> // fcntl
#include <unistd.h>

#include "client.hpp"
Client::Client(int socket) : clientSocket(socket),registered(false),phoneNo(""){
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    getpeername(socket, (struct sockaddr*)&addr, &len);
    address = inet_ntoa(addr.sin_addr);

    std::cout << "Client construct!" << std::endl;
}


Client::Client(): clientSocket(0)
{
    std::cout << "Client default construct!" << std::endl;
}

int Client::receiveData(int socket){
    ssize_t bytesRead = read(clientSocket, buffer, sizeof(buffer) - 1);
    if (bytesRead == -1) {
        if (errno != EAGAIN && errno != EWOULDBLOCK) {
            perror("Error reading from client");
        }
        return -1;
    }else if(bytesRead == 0){
        return 0;
    }

    JT808Header header;
    //解析消息
    if(!message.parse(buffer,bytesRead,header,buffer2)){
        std::cerr << "Parse message error! " << std::endl;
        return bytesRead;
    }

    if(phoneNo.empty()){
        //为什么总是进入这个分支呢？！
        phoneNo = message.decodeBCDPhoneNumber(header.phoneNo);
        std::cout << address << " " << phoneNo << std::endl;
    }

    size_t  msgLen = 0;
    uint8_t result = 0;
    CmdID id = (CmdID)header.id;
    switch (id)
    {
    case CmdID::Register:
        if(header.bodyLength<REGISTER_MIN_LENGTH){
            result = 0x02;
        }else{
             message.parseClientInfo(buffer2+HEADER_MIN_LENGTH,header.bodyLength,clientInfo);
             registered = true;
        }

        header.id = static_cast<uint16_t>(CmdID::RegisterResp);
        header.bodyLength = 3+6;
        //TODO 使用随机数作为authcode
        msgLen = message.registerRespose(header,result,(unsigned char*)"123456",6,buffer);
        std::cout << "Register --> " << (int)result << std::endl;
        if(result==0){
            message.printClientInfo(clientInfo);
        }

        break;
    
    case CmdID::Heartbeat:
        header.id = static_cast<uint16_t>(CmdID::PlatformReply);
        header.bodyLength = 5;
        msgLen = message.commonRespose(header,0,(uint16_t)id,buffer);
        std::cout << "Heartbeat --> " << msgLen << std::endl;
        break;

    default:
        header.id = static_cast<uint16_t>(CmdID::PlatformReply);
        header.bodyLength = 5;
        msgLen = message.commonRespose(header,0,(uint16_t)id,buffer);
        break;
    }

    write(clientSocket, buffer, msgLen);

    return bytesRead;
}